import 'package:flick_video_player/flick_video_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_taotaoshipin/player/flick_multi_manager.dart';
import 'package:flutter_taotaoshipin/player/flick_portrait_controls.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:video_player/video_player.dart';

class FlickMultiPlayer extends StatefulWidget {
  FlickMultiPlayer({
    Key? key,
    required this.url,
    required this.flickMultiManager,
    this.onVideoEnd,
    this.header,
    this.info,
    this.right,
    this.bottom,
    this.progressBarBottomOffset = 74,
  }) : super(key: key);

  final String url;
  final FlickMultiManager flickMultiManager;
  final Function? onVideoEnd;
  Widget? header;
  Widget? info;
  Widget? right;
  Widget? bottom;

  /// 进度条距离底部的偏移
  double? progressBarBottomOffset;

  @override
  _FlickMultiPlayerState createState() => _FlickMultiPlayerState();
}

class _FlickMultiPlayerState extends State<FlickMultiPlayer> {
  late FlickManager flickManager;

  @override
  void initState() {
    flickManager = FlickManager(
      videoPlayerController: VideoPlayerController.network(widget.url)
        ..setLooping(false),
      autoPlay: true,
      onVideoEnd: widget.onVideoEnd,
    );
    widget.flickMultiManager.init(flickManager);

    super.initState();
  }

  @override
  void dispose() {
    widget.flickMultiManager.remove(flickManager);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: ObjectKey(flickManager),
      onVisibilityChanged: (visiblityInfo) {
        if (visiblityInfo.visibleFraction > 0.9) {
          widget.flickMultiManager.play(flickManager);
        }
      },
      child: Container(
        child: FlickVideoPlayer(
          flickManager: flickManager,
          flickVideoWithControls: FlickVideoWithControls(
            // videoFit: BoxFit.contain,
            controls: FeedPlayerPortraitControls(
              flickMultiManager: widget.flickMultiManager,
              flickManager: flickManager,
              header: widget.header,
              info: widget.info,
              right: widget.right,
              bottom: widget.bottom,
              progressBarBottomOffset: widget.progressBarBottomOffset,
            ),
          ),
          flickVideoWithControlsFullscreen: FlickVideoWithControls(
            controls: FlickLandscapeControls(),
            iconThemeData: IconThemeData(
              size: 40,
              color: Colors.white,
            ),
            textStyle: TextStyle(fontSize: 16, color: Colors.white),
          ),
        ),
      ),
    );
  }
}
